<template>
  <div class="wei-container">
    <van-nav-bar class="wei-header van-nav-bar_none van-nav-bar_line">
      <van-icon name="arrow-left"
                slot="left"
                class="break"
                @click="$router.goBack()" />
      <!-- <span slot="right" class="link">
        <router-link :to="{path:'/user/login'}" replace>登录</router-link>
      </span> -->
    </van-nav-bar>
    <div class="wei-wepper">
      <h2 class="wei-title">手机绑定</h2>
      <div class="wei-tip"
           :class="{'is-active':codeFlag}">
        <span v-text="form.username"></span>
        <van-icon name="edit"
                  @click.stop="resetCode"></van-icon>
      </div>
      <van-cell-group class="wei-form">
        <van-field center
                   class="form-item wei-form_phone"
                   v-model="form.username"
                   maxlength="13"
                   v-if="!codeFlag"
                   @keyup.delete="delPhone"
                   placeholder="输入手机号">
        </van-field>
        <div class="wei-code"
             v-else>
          <div class="item"
               v-for="item in 4"
               :key="item"
               @click="keyFlag=true"
               :class="{'is-active':(item-1)<codeLen}"
               v-text="codeList[item-1]"></div>
        </div>
      </van-cell-group>
      <div class="wei-link"
           :class="{'is-active':codeFlag}">
        <span>登录即表明您同意我们的
          <small @click="goPage('http://qt.qq.com/php_cgi/pvp_news/html/license.html','用户协议')">用户协议</small>
        </span>
      </div>
      <div class="wei-footer"
           v-if="!codeFlag">
        <login-footer></login-footer>
      </div>
    </div>
    <div class="wei-keyword">
      <el-button :disabled="timeFlag || phoneFlag"
                 type="success"
                 size="mini"
                 class="code-btn"
                 :class="{'is-active':codeFlag}"
                 @click="sendMobileCode">{{timeFlag?`${time}s 后重发`:'获取验证码'}}</el-button>
      <van-number-keyboard :show="keyFlag"
                           @blur="keyFlag = false"
                           close-button-text="完成"
                           @input="onInput"
                           @delete="onDelete" />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { sendMobileCode, bindUser } from '@/api/user';
import common from './mixins/common.js';
import time from '@/mixins/time.js';
import baseCommon from '@/mixins/common.js';
import { validatenull, asyncValidator } from '@/util/validate';

export default {
  name: 'reg',
  mixins: [common(), baseCommon(), time(60)],
  data () {
    return {
      codeFlag: false,
      keyFlag: false,
      phoneKey: false,
      codeList: [],
      rules: {
        username: { type: 'string', required: true, message: '请输入手机号' },
        mobileCode: { type: 'string', required: true, message: '请输入验证码' },
      },
      form: {
        username: '',
        mobileCode: '',
      },
    };
  },
  watch: {
    'form.username': function (n) {
      const len = n.length;
      if ([4, 9].includes(len) && this.phoneKey) {
        this.form.username = `${this.form.username.substr(0, len - 1)} ${this.form.username.substr(len - 1)}`;
      }
      this.phoneKey = true;
    },
    'form.mobileCode': function (val) {
      if (val.length === 4) {
        this.signIn();
      }
    },
    codeFlag (val) {
      this.keyFlag = val;
    },
    codeLen (val) {
      this.form.mobileCode = this.codeList.join('');
    },
  },
  computed: {
    ...mapGetters(['token', 'userInfo', 'website', 'unionId']),
    codeLen () {
      return this.codeList.length || 0;
    },
    phoneData () {
      return this.form.username.replace(/\s+/g, '');
    },
    phoneFlag () {
      return validatenull(this.form.username) ? true : this.form.username.length !== 13;
    },
  },
  methods: {
    onInput (value) {
      if (this.codeLen === 4) return;
      this.codeList.push(value);
    },
    onDelete () {
      if (this.codeLen === 0) return;
      this.codeList.splice(this.codeLen - 1, 1);
    },
    delPhone () {
      const len = this.form.username.length;
      this.phoneKey = false;
      if ([4, 9].includes(len)) this.form.username = this.form.username.substr(0, len - 1);
    },
    resetCode () {
      this.codeFlag = false;
      this.timeEnd();
    },
    signIn () {
      const form = {
        username: this.form.username,
        mobileCode: this.form.mobileCode,
      };
      asyncValidator(this.rules, form)
        .then(() => bindUser(this.unionId, form.username, form.mobileCode)).then((res) => {
          const data = res.data;
          const success = data.success;
          const msg = data.msg;
          if (!success) {
            this.$message.warning({
              message: msg,
              duration: 1500,
            });
            return Promise.reject();
          }
          return this.$store.dispatch('getAuth');
        })
        .then((res) => {
          const data = res.data;
          return this.$store.dispatch('GetUserInfo');
        })
        .then(() => {
          this.$message.success({
            message: '绑定成功',
            duration: 1500,
          });
          setTimeout(() => {
            this.goAuth();
          }, 500);
        })
        .catch((errors) => {
          this.$message.warning({
            message: errors[0].message,
            duration: 1500,
          });
        });
    },
    sendMobileCode () {
      if (validatenull(this.form.username)) {
        this.$message.warning({
          message: '请输入手机号',
          duration: 1500,
        });
        return;
      }
      sendMobileCode(this.form.username).then((res) => {
        this.timeInit();
        this.form.mobileCode = res.data.data;
        this.$message.success({
          message: '验证码发送成功',
          duration: 1500,
        });
      });
    },
    passwordView () {
      if (!this.type) {
        this.type = 'password';
      } else {
        this.type = undefined;
      }
    },
  },
};
</script>

<style lang="scss">
@import './css/login.scss';
.code-btn {
  width: 97px;
  height: 42px;
  font-size: 14px;
}
</style>

